package com.redis.springbootredis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.net.UnknownHostException;

/**
 * @author
 * @create 2020-10-29 22:07
 * 配置类，为了解决系统定义的类单一且不好用的问题
 * 为了遵循redis的规范，将key值设定为String，value设置为Object
 */

@Configuration
public class RedisAutoConfiguration {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        //设置所所有Value的序列化器为json类型
        template.setValueSerializer(RedisSerializer.json());
        //设置Hash的field使用String序列化
        template.setHashKeySerializer(RedisSerializer.string());
        //所有key值都使用String
        template.setKeySerializer(RedisSerializer.string());
        //设置Hash的Value为json序列化
        template.setHashValueSerializer(RedisSerializer.json());
        return template;
    }
}
